package com.lily.agent;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.objectweb.asm.ClassReader;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.*;

public class ClassDumpTransformer implements ClassFileTransformer {
    private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
    private final List<Map<String, Object>> classInfoList = new ArrayList<>();

    public byte[] transform(ClassLoader loader,
                            String className,
                            Class redefinedClass,
                            ProtectionDomain protDomain,
                            byte[] classfileBuffer) throws IllegalClassFormatException {

        if (ClassDumpUtils.isCandidate(className)) {
            try {
                ClassReader cr = new ClassReader(classfileBuffer);
                ClassInfoCollector cv = new ClassInfoCollector();
                cr.accept(cv, 0);
                classInfoList.add(cv.getClassInfo());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return classfileBuffer;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        exportToJson();
    }

    public void exportToJson() {
        try (FileWriter writer = new FileWriter(ClassDumpUtils.getDumpDir() + File.separator + "class_info.json")) {
            System.out.println("--------------------------------------------------------shit----------------------------------------------------------");
            gson.toJson(classInfoList, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}